package com.ruoyi.project.enable;

import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

@Slf4j
public class AutoEnhanceAdvice implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {

        Method method = invocation.getMethod();
        Object[] args = invocation.getArguments();

        log.info("invoke method:"+method.getName()+" ----args:"+argsToString(args));

        Object obj = invocation.proceed();

        log.info("invoke method:"+method.getName()+" ----return:"+argsToString(obj));
        return  obj;
    }

    private String argsToString(Object... args){
        if(null==args){
            return "null";
        }

        return Arrays.stream(args).map(obj->{
            if(null==obj){
                return "null";
            }else{
                return obj.toString();
            }
        }).collect(Collectors.joining(","));
    }


//    @Override
//    public Object invoke(MethodInvocation invocation) throws Throwable {
//        //拦截原生DataSource，放入代理数据源
//        DataSourceProxy dataSourceProxy = DataSourceProxyHolder.get().putDataSource((DataSource) invocation.getThis());
//        Method method = invocation.getMethod();
//        Object[] args = invocation.getArguments();
//        //代理类获取方法，获取到了走代理逻辑，否则走原生逻辑
//        Method m = BeanUtils.findDeclaredMethod(DataSourceProxy.class, method.getName(), method.getParameterTypes());
//        if (null != m) {
//            return m.invoke(dataSourceProxy, args);
//        } else {
//            return invocation.proceed();
//        }
//    }

}
